package com.autogo

import android.app.Activity
import android.content.Intent
import android.provider.Settings
import android.accessibilityservice.AccessibilityServiceInfo
import android.view.accessibility.AccessibilityManager
import android.widget.Toast
import com.facebook.react.bridge.*
import com.facebook.react.modules.core.DeviceEventManagerModule
import android.os.Handler
import android.os.Looper

/**
 * AutoGo React Native 原生模块
 * 用于桥接 JS 层与 AutoGoAccessibilityService
 */
class AutoGoModule(private val reactContext: ReactApplicationContext) :
    ReactContextBaseJavaModule(reactContext) {

    override fun getName() = "AutoGoModule"

    // -------------------------------
    // Handler 管理动作队列
    // -------------------------------
    private val mainHandler = Handler(Looper.getMainLooper())
    private val pendingRunnables = mutableListOf<Runnable>()

    // -------------------------------
    // 修复 NativeEventEmitter 警告
    // -------------------------------
    @ReactMethod
    fun addListener(eventName: String) { }

    @ReactMethod
    fun removeListeners(count: Int) { }

    // -------------------------------
    // 权限检查
    // -------------------------------
    @ReactMethod
    fun isAccessibilityServiceEnabled(promise: Promise) {
        try {
            val am = reactContext.getSystemService(AccessibilityManager::class.java)
            val enabledServices =
                am.getEnabledAccessibilityServiceList(AccessibilityServiceInfo.FEEDBACK_ALL_MASK)

            val targetClass = AutoGoAccessibilityService::class.java.name
            val enabled = enabledServices.any { it.resolveInfo.serviceInfo.name == targetClass }
            promise.resolve(enabled)
        } catch (e: Exception) {
            promise.reject("ACCESSIBILITY_CHECK_ERROR", e)
        }
    }

    @ReactMethod
    fun openAccessibilitySettings() {
        val intent = Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        reactContext.startActivity(intent)
        showToast("请在列表中开启 AutoGo 服务")
    }

    // -------------------------------
    // 最小化 App（主线程安全）
    // -------------------------------
    @ReactMethod
    fun minimizeApp(promise: Promise) {
        minimizeAppWithDelay(1000, promise)
    }

    @ReactMethod
    fun minimizeAppWithDelay(delay: Int?, promise: Promise) {
        val activity = reactContext.currentActivity
        if (activity == null) {
            promise.reject("NO_ACTIVITY", "Current activity is null")
            showToast("❌ 无法最小化：Activity 不存在")
            return
        }

        mainHandler.postDelayed({
            try {
                activity.moveTaskToBack(true)
                promise.resolve(true)
            } catch (e: Exception) {
                promise.reject("MINIMIZE_APP_ERROR", e)
            }
        }, (delay ?: 1000).toLong())
    }

    // -------------------------------
    // 安全执行动作序列
    // -------------------------------
    @ReactMethod
    fun runActions(actions: ReadableArray, promise: Promise) {
        val service = AutoGoServiceHolder.serviceInstance
        if (service == null) {
            showToast("❌ 无障碍服务未连接，无法执行动作")
            promise.reject("NO_SERVICE", "AccessibilityService 未连接")
            return
        }

        // 清空上一次残留的任务（防止重复）
        stopActionsInternal()

        var totalDelay: Long = 0

        for (i in 0 until actions.size()) {
            val action = actions.getMap(i) ?: continue
            val name = action.getString("name") ?: continue
            val delay = action.getDouble("delay").toLong()
            totalDelay += delay

            val runnable = Runnable {
                try {
                    when (name) {
                        "swipeUp" -> service.performSwipe("up")
                        "swipeDown" -> service.performSwipe("down")
                        "click" -> {
                            val x = action.getDouble("x").toFloat()
                            val y = action.getDouble("y").toFloat()
                            service.performClick(x, y)
                        }
                        else -> showToast("❌ 未知动作：$name")
                    }

                    // 最后一个动作完成时通知前端
                    if (i == actions.size() - 1) {
                        reactContext
                            .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
                            .emit("onScriptFinished", null)
                        promise.resolve(true)
                    }

                } catch (e: Exception) {
                    promise.reject("RUN_ACTIONS_ERROR", e)
                }
            }

            pendingRunnables.add(runnable)
            mainHandler.postDelayed(runnable, totalDelay)
        }
    }

    // -------------------------------
    // 停止正在执行的动作
    // -------------------------------
    @ReactMethod
    fun stopActions() {
        stopActionsInternal()
        showToast("动作序列已停止")
        reactContext
            .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
            .emit("onScriptStopped", null)
    }

    private fun stopActionsInternal() {
        for (runnable in pendingRunnables) {
            mainHandler.removeCallbacks(runnable)
        }
        pendingRunnables.clear()
    }

    // -------------------------------
    // 辅助方法
    // -------------------------------
    private fun showToast(msg: String) {
        mainHandler.post {
            Toast.makeText(reactContext, msg, Toast.LENGTH_SHORT).show()
        }
    }
}
